package com.dream.utils.web.provider;

import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2012/09/22
 */
public class SpringContextUtils {

	/**
	 * get spring beans by class type
	 * @param context
	 * @param type
	 * @return
	 */
	public static <T> T getBean(ServletContext context, Class<T> type) {

		Map<String, T> beans = WebApplicationContextUtils.getWebApplicationContext(context).getBeansOfType(type);

		if (beans.isEmpty()) {
			return null;
		} else {
			return (T)beans.values().iterator().next();
		}
	}
	
	/**
	 * get bean by name
	 * @param context
	 * @param beanName
	 * @param type
	 * @return
	 */
	public static <T> T getBean(ServletContext context, String beanName,Class<T> type) {

		T obj = WebApplicationContextUtils.getWebApplicationContext(context).getBean(beanName,type);
		return obj;
	}
	
	public static <T> T getBean(String beanName,Class<T> type){
		
		WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
		T obj = context.getBean(beanName, type);
		return obj;
	}
	
	public static <T> T getBean(ApplicationContext context,String beanName,Class<T> type){
		
		T obj = context.getBean(beanName, type);
		return obj;
	}
}
